//
//  main.m
//  Day10test
//
//  Created by dllo on 16/5/17.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    
#if 0
    char a[] = "a3b2c4b56";
    //先求出字符串中有多少个数字
    int count = 0;
    for(int i = 0; i < 10 ;i++) {
        if (a[i] <= '9' && a[i] >= '0') {
            count++;
        }
    }
    //根据数字个数动态分配内存
    //+1  是给'\0' 留出位置
    int x = 0;  //记录数字的位置
    char *p = malloc(sizeof(char) * (count + 1));
    if (p == NULL) {
        printf("内存申请失败");
        return 0;
    } else {
    for(int i = 0; i < 10 ;i++) {
        if (a[i] <= '9' && a[i] >= '0') {
            *(p + x) = a[i];
            x++;
        }
    }
    // 将指针的最后一块地址保存'\0'
    *(p + count + 1) = '\0';
    
    printf("%s\n",p);
    // 改变堆区内存状态
    free(p);
    // 置空指针
    p = NULL;
    }
#endif
    
#if 0
    char str1[20];
    char str2[20];
    char str3[20];
    char *str[3] = {str1 ,str2, str3};
    
    printf("请输入三个字符串\n");
    for (int i = 0;i < 3; i++){
        scanf("%s",str[i]);
    }
    char *words[3] = {0};
    for (int i = 0; i < 3; i++) {
        words[i] = malloc(sizeof(char) * (strlen(str[i]) + 1));
    }
    
    for(int i = 0; i < 3 ;i++) {
        strcpy(words[i], str[i]);
    }
    printf("您输入的单词是:\n");
    for(int j = 0; j < 3; j++) {
        printf("%s\n",words[j]);
    }
    free(words);
    *words = NULL;
    
    
    
    
#endif
    
#if 0    
    char scanfStr[255] = {0};
    char *str[3] = {0};
   // char *words[3] = {0};
    
    for (int i = 0; i < 3; i++) {
        printf("输入一个单词:\n");
        scanf("%s", scanfStr);
        //输入字符串的长度
        unsigned long length = strlen(scanfStr);
        
        //动态内存分配
        char *p =malloc(sizeof(char) * (length + 1));
        //把输入的单词存入申请的空间内
        strcpy(p, scanfStr);
        //把当前输入单词的对应地址赋给指针数组
        str[i] = p;
        printf("%s\n", str[i]);

        free(p);
        p = NULL;
    }
    
#endif
    
    
#if 0
    // 1.野指针 访问坏掉 (不存在) 的内存 ,对野指针进行操作是非常危险的
    int *p = malloc(3);
    free(p);
    p = NULL;
    // EXC_BAD_ACCESS   访问野指针
    *p = 'a';
    
    
    
    // 2.过度释放
//    char *p = malloc(3);
//    free(p);
//    free(p);
    
    // 3.内存泄露
    
    
#endif
    
    return 0;
}
